import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

public class MqttSubscriber {
    // MQTT服务器地址
    private static final String BROKER = "tcp://localhost:1883";
    // 客户端ID
    private static final String SUBSCRIBER_ID = "java-subscriber";
    // 主题
    private static final String TOPIC = "test/topic";

    public static void main(String[] args) {
        MemoryPersistence persistence = new MemoryPersistence();

        try {
            // 创建客户端
            MqttClient client = new MqttClient(BROKER, SUBSCRIBER_ID, persistence);

            // 连接选项
            MqttConnectOptions connOpts = new MqttConnectOptions();
            connOpts.setCleanSession(true);

            // 如果服务器需要认证，添加用户名密码
             connOpts.setUserName("your_mqtt_username");
             connOpts.setPassword("your_mqtt_password".toCharArray());

            // 设置回调函数处理接收到的消息
            client.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable cause) {
                    System.out.println("连接丢失: " + cause.getMessage());
                    // 可以在这里实现重连逻辑
                }

                @Override
                public void messageArrived(String topic, MqttMessage message) throws Exception {
                    System.out.println("接收到消息 - 主题: " + topic
                            + " 内容: " + new String(message.getPayload())
                            + " QoS: " + message.getQos());
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                    // 对于订阅者来说，这个方法通常不需要实现
                }
            });
            // 连接服务器
            System.out.println("连接到MQTT服务器: " + BROKER);
            client.connect(connOpts);
            System.out.println("连接成功");

            // 订阅主题
            System.out.println("订阅主题: " + TOPIC);
            client.subscribe(TOPIC, 1); // 第二个参数是QoS级别

            // 保持连接以接收消息，这里简单休眠一段时间
            Thread.sleep(60000); // 保持连接60秒

            // 断开连接
            client.disconnect();
            System.out.println("已断开连接");

        } catch (MqttSecurityException e) {
            System.out.println("MQTT安全异常: " + e.getMessage());
            System.out.println("错误代码: " + e.getReasonCode());
            e.printStackTrace();
        } catch (MqttException e) {
            System.out.println("MQTT异常: " + e.getMessage());
            System.out.println("错误代码: " + e.getReasonCode());
            e.printStackTrace();
        } catch (InterruptedException e) {
            System.out.println("线程中断: " + e.getMessage());
            Thread.currentThread().interrupt(); // 恢复中断状态
        }
    }
}
